package com.cowealth.platform.common.poi.util;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.ExcelBatchExportService;
import cn.afterturn.easypoi.handler.inter.IExcelExportServer;
import com.cowealth.platform.common.poi.base.SubExcelExportService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.Collection;
import java.util.List;

/**
 * Excel导出工具类
 * 完全参照easypoi的 {@link cn.afterturn.easypoi.excel.ExcelExportUtil}
 *
 * @author : skycdm
 * @version : 1.0.0
 * @date : 2021/5/11 11:26
 */
public class ExcelExportUtil {

    public static int USE_SXSSF_LIMIT = 100000;
    public static final String SHEET_NAME = "sheetName";

    private ExcelExportUtil() {
    }

    public static Workbook exportBigExcel(ExportParams entity, Class<?> pojoClass, IExcelExportServer server, Object queryParams) {
        ExcelBatchExportService batchServer = new ExcelBatchExportService();
        batchServer.init(entity, pojoClass);
        return batchServer.exportBigExcel(server, queryParams);
    }

    public static Workbook exportBigExcel(ExportParams entity, List<ExcelExportEntity> excelParams, IExcelExportServer server, Object queryParams) {
        ExcelBatchExportService batchServer = new ExcelBatchExportService();
        batchServer.init(entity, excelParams);
        return batchServer.exportBigExcel(server, queryParams);
    }

    public static Workbook exportExcel(ExportParams entity, Class<?> pojoClass, Collection<?> dataSet) {
        Workbook workbook = getWorkbook(entity.getType(), dataSet.size());
        (new SubExcelExportService()).createSheet(workbook, entity, pojoClass, dataSet);
        return workbook;
    }

    private static Workbook getWorkbook(ExcelType type, int size) {
        if (ExcelType.HSSF.equals(type)) {
            return new HSSFWorkbook();
        } else {
            return (Workbook)(size < USE_SXSSF_LIMIT ? new XSSFWorkbook() : new SXSSFWorkbook());
        }
    }

    public static Workbook exportExcel(ExportParams entity, List<ExcelExportEntity> entityList, Collection<?> dataSet) {
        Workbook workbook = getWorkbook(entity.getType(), dataSet.size());
        (new SubExcelExportService()).createSheetForMap(workbook, entity, entityList, dataSet);
        return workbook;
    }

}
